import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isAuthenticated: localStorage.getItem('isAuthenticated') === 'true' || false,
    userRole: localStorage.getItem('userRole') || '',
    userInfo: JSON.parse(localStorage.getItem('currentUser')) || null,
    blockchainAccount: localStorage.getItem('blockchainAccount') || null,
    registeredUsers: JSON.parse(localStorage.getItem('registeredUsers')) || []
  }),
  
  actions: {
    // 新增：设置用户信息
    setUserInfo(updatedInfo) {
      if (!this.userInfo) return
      
      // 更新当前用户信息
      this.userInfo = { 
        ...this.userInfo, 
        ...updatedInfo 
      }
      
      // 更新注册用户列表
      const userIndex = this.registeredUsers.findIndex(
        u => u.username === this.userInfo.username
      )
      
      if (userIndex !== -1) {
        const updatedUsers = [...this.registeredUsers]
        updatedUsers[userIndex] = { 
          ...updatedUsers[userIndex], 
          ...updatedInfo,
          // 保留原始密码和角色信息
          password: updatedUsers[userIndex].password,
          role: updatedUsers[userIndex].role,
          blockchainAccount: updatedUsers[userIndex].blockchainAccount
        }
        
        this.registeredUsers = updatedUsers
        localStorage.setItem('registeredUsers', JSON.stringify(updatedUsers))
      }
      
      // 更新当前用户存储
      localStorage.setItem('currentUser', JSON.stringify(this.userInfo))
      
      return this.userInfo
    },
    
    // 登录方法
    login(credentials) {
      const { username, password, role } = credentials;
      
      // 1. 验证用户存在性
      const userExists = this.registeredUsers.some(
        user => user.username === username
      );
      if (!userExists) {
        throw new Error('用户不存在，请先注册');
      }

      // 2. 验证用户凭证
      const validUser = this.registeredUsers.find(
        user => user.username === username && user.password === password
      );
      
      if (!validUser) {
        throw new Error('用户名或密码错误');
      }
      
      // 3. 验证用户角色
      if (validUser.role !== role) {
        throw new Error(`角色不匹配，该用户为${validUser.role}身份`);
      }

      // 所有验证通过后登录
      this.isAuthenticated = true;
      this.userRole = role;
      this.userInfo = validUser;
      this.blockchainAccount = validUser.blockchainAccount || null;

      // 更新本地存储
      localStorage.setItem('isAuthenticated', 'true');
      localStorage.setItem('userRole', role);
      localStorage.setItem('currentUser', JSON.stringify(validUser));
      localStorage.setItem('blockchainAccount', this.blockchainAccount);
      
      return true;
    },
    
    // 登出方法
    logout() {
      this.isAuthenticated = false;
      this.userRole = '';
      this.userInfo = null;
      this.blockchainAccount = null;

      localStorage.removeItem('isAuthenticated');
      localStorage.removeItem('userRole');
      localStorage.removeItem('currentUser');
      localStorage.removeItem('blockchainAccount');
    },
    
    // 注册方法
    register(userData) {
      const { username, password, role, blockchainAccount } = userData;
      
      // 检查用户是否已存在
      if (this.registeredUsers.some(user => user.username === username)) {
        throw new Error('该用户名已被注册');
      }

      // 创建完整用户对象
      const newUser = {
        username,
        password,
        role,
        blockchainAccount,
        timestamp: new Date().toISOString(),
        // 初始化用户信息字段
        phone: '',
        realName: '',
        age: '',
        idCard: '',
        medicalHistory: '',
        bloodType: '',
        allergies: '',
        chronicDiseases: '',
        primaryDoctor: ''
      };

      this.registeredUsers.push(newUser);
      localStorage.setItem('registeredUsers', JSON.stringify(this.registeredUsers));
      
      // 自动登录新注册用户
      this.login({ username, password, role });
      
      return newUser;
    },
    
    // 实用方法
    isUserRegistered(username) {
      return this.registeredUsers.some(user => user.username === username);
    },
    
    getUserRole(username) {
      const user = this.registeredUsers.find(u => u.username === username);
      return user ? user.role : null;
    }
  }
})